package com.hotel.customersystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.status.ResultMsg;
import com.hotel.config.rabbitmq.config.RedisUnReadWebSocketConfig;
import com.hotel.couponsystem.mapper.CouponStockMapper;
import com.hotel.couponsystem.pojo.CouponStock;
import com.hotel.customersystem.mapper.CustomerUserCouponMapper;
import com.hotel.customersystem.mapper.CustomerUserMapper;
import com.hotel.customersystem.pojo.CustomerUser;
import com.hotel.customersystem.pojo.CustomerUserCoupon;
import com.hotel.customersystem.service.CustomerUserCouponService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * (CustomerUserCoupon)表服务实现类
 *
 * @author makejava
 * @since 2022-09-30 16:33:50
 */
@Service("customerUserCouponService")
public class CustomerUserCouponServiceImpl extends ServiceImpl<CustomerUserCouponMapper, CustomerUserCoupon> implements CustomerUserCouponService {

    @Resource
    private CustomerUserCouponMapper customerUserCouponMapper;
    @Resource
    private CouponStockMapper couponStockMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CustomerUserMapper customerUserMapper;

    /*根据用户账号查询用户个人优惠券库存表*/
    @Override
    public List<CustomerUserCoupon> getByUserAdmin(String userAdmin) {
        List<CustomerUserCoupon> couponList = customerUserCouponMapper.getUserAdmin(userAdmin);
        // 已过期的优惠券状态设置为2--已过期
        couponList.forEach(s->{
            if (s.getInvalidTime().isAfter(LocalDateTime.now())) s.setCouponUseStatus(2);
        });
        return couponList;
    }

    @Override
    public Boolean updateCouponByCouponNo(Integer couponNo) {
        Integer rows = customerUserCouponMapper.updateByCouponNo(couponNo);
        return rows > 0;
    }

    @Override
    public List<CustomerUserCoupon> getByUserIdNotUse(Integer userId) {
        LambdaQueryWrapper<CustomerUser> ldq = new LambdaQueryWrapper<>();
        ldq.eq(CustomerUser::getUserId,userId);
        CustomerUser customerUser = customerUserMapper.selectOne(ldq);
        QueryWrapper<CustomerUserCoupon> qw = new QueryWrapper<>();
        qw.eq("standby01",customerUser.getStandby01()).eq("coupon_use_status",0).orderByAsc("receive_time");
        List<CustomerUserCoupon> customerUserCoupons = customerUserCouponMapper.selectList(qw);
        for (CustomerUserCoupon customerUserCoupon : customerUserCoupons) {
            CouponStock couponStock = couponStockMapper.selectByCouponNo(Integer.valueOf(customerUserCoupon.getCouponNo()));
            customerUserCoupon.setCouponName(couponStock.getCouponName());
            customerUserCoupon.setCouponPrice(couponStock.getCouponPrice());
            customerUserCoupon.setCouponFullPrice(couponStock.getCouponFullPrice());
            customerUserCoupon.setCouponDiscount(couponStock.getCouponDiscount());
            customerUserCoupon.setBeginTime(customerUserCoupon.getReceiveTime().toLocalDate());
            customerUserCoupon.setEndTime(customerUserCoupon.getInvalidTime().toLocalDate());
        }
        return customerUserCoupons;
    }

    @Override
    public List<CustomerUserCoupon> getByUserIdHaveUsed(Integer userId) {
        LambdaQueryWrapper<CustomerUser> ldq = new LambdaQueryWrapper<>();
        ldq.eq(CustomerUser::getUserId,userId);
        CustomerUser customerUser = customerUserMapper.selectOne(ldq);
        QueryWrapper<CustomerUserCoupon> qw = new QueryWrapper<>();
        qw.eq("standby01",customerUser.getStandby01()).eq("coupon_use_status",0).orderByAsc("receive_time");
        List<CustomerUserCoupon> customerUserCoupons = customerUserCouponMapper.selectList(qw);
        for (CustomerUserCoupon customerUserCoupon : customerUserCoupons) {
            CouponStock couponStock = couponStockMapper.selectByCouponNo(Integer.valueOf(customerUserCoupon.getCouponNo()));
            customerUserCoupon.setCouponName(couponStock.getCouponName());
            customerUserCoupon.setCouponPrice(couponStock.getCouponPrice());
            customerUserCoupon.setCouponFullPrice(couponStock.getCouponFullPrice());
            customerUserCoupon.setCouponDiscount(couponStock.getCouponDiscount());
            customerUserCoupon.setBeginTime(customerUserCoupon.getReceiveTime().toLocalDate());
            customerUserCoupon.setEndTime(customerUserCoupon.getInvalidTime().toLocalDate());
        }
        return customerUserCoupons;
    }

    @Override
    public String saveWebSocketRedis(String userId, String message) {
        //存入redis的key
        String userUnreadMessage = "userUnreadMessage:"+userId;
        redisTemplate.opsForSet().add(userUnreadMessage,message);
        return ResultMsg.WEBSOCKET_MESSAGE_USER_UNREAD;
    }

    @Override
    public Boolean getRedisToWebSocket(String userId) {
        System.out.println("操作redis对应的消息队列中...");
        //存入redis的key
        String userUnreadMessage = "userUnreadMessage:"+userId;
        //读取到所有redis当中存储的未被读取的消息
        System.out.println("滞留在redis中的消息数量: "+redisTemplate.opsForSet().size(userUnreadMessage));
        for (int i = 0; i < redisTemplate.opsForSet().size(userUnreadMessage); i++) {
            //每次读取一个进入消息队列当
            String str = redisTemplate.opsForSet().pop(userUnreadMessage).toString();
//            String str1 = redisTemplate.opsForSet().pop(userUnreadMessage).toString();
            System.out.println("消息1"+str);
//            System.out.println("消息2"+str1);
            MessageProperties messageProperties = new MessageProperties();
            Message message = new Message((str+"-"+userId).getBytes(),messageProperties);
            rabbitTemplate.convertAndSend(RedisUnReadWebSocketConfig.READ_REDIS_TO_WEBSOCKET_EXCHANGE,RedisUnReadWebSocketConfig.READ_REDIS_TO_WEBSOCKET_KEY,message);
        }
        return true;
    }
}

